package com.unohacha.qqj.fzdr.main;

import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.unohacha.qqj.fzdr.R;
import com.unohacha.qqj.fzdr.adapter.BaseRVAdapter;
import com.unohacha.qqj.fzdr.adapter.BaseViewHolder;
import com.unohacha.qqj.fzdr.bean.homebean.HomeAppMaterialCateBean;
import com.unohacha.qqj.fzdr.bean.homebean.HomeAppMaterialListBean;
import com.unohacha.qqj.fzdr.bean.homebean.HomeBannerBean;
import com.unohacha.qqj.fzdr.fragment.MaterialInfoActivity;
import com.unohacha.qqj.fzdr.imp.MyApplication;
import com.unohacha.qqj.fzdr.imp.MyCallBack;
import com.unohacha.qqj.fzdr.imp.UrlConfig;
import com.unohacha.qqj.fzdr.imp.XUtil;
import com.unohacha.qqj.fzdr.main.sends.SendMaterialMarketActivity;
import com.unohacha.qqj.fzdr.personal.view.activity.MaterialDetailActivity;
import com.unohacha.qqj.fzdr.util.GlideImageLoader;
import com.unohacha.qqj.fzdr.util.Prefer;
import com.unohacha.qqj.fzdr.util.ToastUtils;
import com.unohacha.qqj.mylibrary.base.BaseActivity;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 物资行情 item_material
 */
public class MaterialActivity extends BaseActivity implements OnRefreshLoadmoreListener {

    @BindView(R.id.common_back)
    ImageView commonBack;
    @BindView(R.id.common_title)
    TextView commonTitle;
    @BindView(R.id.common_right_image)
    ImageView commonRightImage;
    @BindView(R.id.common_right_text)
    TextView commonRightText;
    @BindView(R.id.title_ll)
    LinearLayout titleLl;
    @BindView(R.id.common_cancle)
    ImageView commonCancle;
    @BindView(R.id.edt_seach)
    EditText edtSeach;
    @BindView(R.id.common_right_search)
    TextView commonRightSearch;
    @BindView(R.id.search_ll)
    LinearLayout searchLl;
    @BindView(R.id.pt_tabs)
    TabLayout mTabLayout;
    @BindView(R.id.pt_line)
    ImageView ptLine;
    @BindView(R.id.car_list_recycler)
    RecyclerView carListRecycler;
    @BindView(R.id.mRefreshLayout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.send_iv)
    ImageView sendIv;
    @BindView(R.id.banner)
    Banner banner;

    private List<String> mFragmentsTitle = new ArrayList<>();//碎片的标题
    private List<HomeAppMaterialCateBean.DataBean> mAppCateList = new ArrayList<>();//标题的集合
    private List<HomeAppMaterialListBean.DataBeanX.DataBean> mAppDataList = new ArrayList<>();
    private List<HomeBannerBean.DataBean> mBannerAllList = new ArrayList<>();//banner的集合
    private List<String> mBannerList = new ArrayList<>();
    private String type = "0";
    private String address_id;//地区ID
    private int app_cate_id;//分类ID
    private int page = 1;
    private BaseRVAdapter mBaseAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_material;
    }

    @Override
    protected void initView() {
        super.initView();
        commonTitle.setText(getResources().getString(R.string.material_info));
        commonRightText.setVisibility(View.GONE);
        if (null != getIntent()) {
            address_id = getIntent().getStringExtra("address_id");
            app_cate_id = getIntent().getIntExtra("app_cate_id", 0);
        }
        initRefreshLayout();
        getAppMaterialCate();
        getBannerData(30);
    }

    private void initRefreshLayout() {
        mRefreshLayout.setOnRefreshLoadmoreListener(this);
        mRefreshLayout.setRefreshHeader(new ClassicsHeader(this));
        mRefreshLayout.setRefreshFooter(new ClassicsFooter(this));
        carListRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        carListRecycler.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
    }

    //初始化tab
    private void initTabLayout(List<String> mFragmentsTitle0) {

        for (int i = 0; i < mFragmentsTitle0.size(); i++) {
            mTabLayout.addTab(mTabLayout.newTab().setText(mFragmentsTitle.get(i)), i);
        }
        if (null != mAppCateList) {
            app_cate_id = mAppCateList.get(0).getId();
        }
        getAppMaterialData("");
        mTabLayout.setSelectedTabIndicatorColor(getResources().getColor(R.color.black));
        mTabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
        mTabLayout.setTabMode(TabLayout.MODE_FIXED);
        mTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (null != mAppCateList) {
                    app_cate_id = mAppCateList.get(tab.getPosition()).getId();
                    page = 1;
                    Log.d("app_cate_id",app_cate_id+"");
                    getAppMaterialData("");
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }

    //物资行情分类
    private void getAppMaterialCate() {
        XUtil.Post(UrlConfig.APP_MATERIAL_CATE, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (1 == jsonObject.optInt("code")) {
                        Gson gson = new Gson();
                        HomeAppMaterialCateBean cateBean = gson.fromJson(result, HomeAppMaterialCateBean.class);
                        if (null != cateBean) {
                            if (null != mAppCateList) {
                                mAppCateList.clear();
                            }
                            mAppCateList.addAll(cateBean.getData());
                            for (int i = 0; i < mAppCateList.size(); i++) {
                                mFragmentsTitle.add(i, mAppCateList.get(i).getName());
                            }
                            initTabLayout(mFragmentsTitle);
                        }
                    } else if (100 == jsonObject.optInt("code")) {
                        MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    } else {
                        MyToast(jsonObject.optString("message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    //获取物资行情列表
    private void getAppMaterialData(String keyword) {
        showLoading();
        Map<String, Object> params = new HashMap<>();
        params.put("app_cate_id", app_cate_id);
        params.put("address_id", address_id);
        params.put("keyword", keyword);
        params.put("page", page);
        XUtil.Post(UrlConfig.APP_MATERIAL_LIST, params, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (1 == jsonObject.optInt("code")) {
                        Gson gson = new Gson();
                        HomeAppMaterialListBean listBean = gson.fromJson(result, HomeAppMaterialListBean.class);
                        if (null != listBean) {
                            if (page == 1) {
                                mRefreshLayout.finishRefresh();
                                mRefreshLayout.resetNoMoreData();
                                if (null != mAppDataList) {
                                    mAppDataList.clear();
                                }
                                mAppDataList.addAll(listBean.getData().getData());
                            } else {
                                mRefreshLayout.finishLoadmore();
                                mBaseAdapter.notifyDataSetChanged();
                            }
                            setAppDataListAdapter();
                        }
                    } else if (100 == jsonObject.optInt("code")) {
                        MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    } else {
                        if (page == 1) {
                            MyToast(jsonObject.optString("message"));
                            mRefreshLayout.finishRefresh();
                            mRefreshLayout.resetNoMoreData();
                            if (null != mAppDataList) {
                                mAppDataList.clear();
                            }
                            mBaseAdapter.notifyDataSetChanged();
                        } else {
                            MyToast(getResources().getString(R.string.no_more_data));
                            mRefreshLayout.finishLoadmore();
                            mRefreshLayout.finishLoadmoreWithNoMoreData();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                hideLoading();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                hideLoading();
            }
        });
    }

    //设置物资行情列表数据
    private void setAppDataListAdapter() {
        mBaseAdapter = new BaseRVAdapter(this, mAppDataList) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_material;
            }

            @Override
            public void onBind(BaseViewHolder holder, int position) {
                TextView tv_name = holder.getTextView(R.id.tv_name);
                TextView tv_price = holder.getTextView(R.id.tv_price);
                if (null != mAppDataList) {
                    tv_name.setText(mAppDataList.get(position).getName());
                    tv_price.setText("参考价格:" + "¥" + mAppDataList.get(position).getMin() + "元/吨"
                            + "¥" + mAppDataList.get(position).getMax() + "元/吨");
                }
            }
        };
        carListRecycler.setAdapter(mBaseAdapter);
        mBaseAdapter.addItemClickListener(new BaseRVAdapter.OnItemClickListener() {
            @Override
            public void itemSelect(int position) {
                Intent intent = new Intent(MaterialActivity.this, MaterialDetailActivity.class);
                intent.putExtra("address_id", address_id + "");
                intent.putExtra("id", mAppDataList.get(position).getId() + "");
                intent.putExtra("name", mAppDataList.get(position).getName() + "");
                intent.putExtra("type", mFragmentsTitle.get(mTabLayout.getSelectedTabPosition()) + "");
                startActivity(intent);
            }
        });
    }

    //获取banner 集合数据
    private void getBannerData(int typeid) {
        Map<String, Object> params = new HashMap<>();
        params.put("token", Prefer.getInstance().getToken());
        params.put("typeid", typeid);//4-面料供求 5-制造供求 6-原料供求 7-辅料供应 8-人才招聘 29-求职发布
        XUtil.Post(UrlConfig.AD_LIST, params, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    mRefreshLayout.finishRefresh();
                    mRefreshLayout.resetNoMoreData();
                    JSONObject jsonObject = new JSONObject(result);
                    if ("1".equals(jsonObject.optString("code"))) {
                        Gson gson = new Gson();
                        HomeBannerBean bannerBean = gson.fromJson(result, HomeBannerBean.class);
                        if (null != bannerBean) {
                            if (null != mBannerAllList) {
                                mBannerAllList.clear();
                            }
                            mBannerAllList.addAll(bannerBean.getData());
                            setBannerData();
                        }
                        mRefreshLayout.finishLoadmore();
                        mRefreshLayout.finishLoadmoreWithNoMoreData();
                    } else if ("100".equals(jsonObject.optString("code"))) {
                        MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    } else {
                        MyToast(jsonObject.optString("message"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    //设置banner 数据
    private void setBannerData() {
        if (null != mBannerAllList) {
            for (int i = 0; i < mBannerAllList.size(); i++) {
                mBannerList.add(i, mBannerAllList.get(i).getImg_face());
            }
            banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);//设置圆形指示器与标题
            banner.setIndicatorGravity(BannerConfig.CENTER);//设置指示器位置
            banner.setImages(mBannerList);
            banner.setImageLoader(new GlideImageLoader());
            banner.start();

            banner.setOnBannerListener(new OnBannerListener() {
                @Override
                public void OnBannerClick(int position) {
                    //用mBannerAllList集合
                }
            });
        }
    }


    @OnClick({R.id.common_back, R.id.common_right_text,
            R.id.common_right_image, R.id.common_cancle,
            R.id.common_right_search,R.id.send_iv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.common_back:
                finish();
                break;
            case R.id.common_right_image://搜索图片
                searchLl.setVisibility(View.VISIBLE);
                edtSeach.setText("");
                titleLl.setVisibility(View.GONE);
                break;
            case R.id.common_cancle://取消
                searchLl.setVisibility(View.GONE);
                titleLl.setVisibility(View.VISIBLE);
                edtSeach.setText("");
                break;
            case R.id.common_right_search://搜索按钮
                if (!TextUtils.isEmpty(edtSeach.getText().toString().trim())) {
                    getAppMaterialData(edtSeach.getText().toString().trim());
                } else {
                    MyToast("请输入搜索内容!");
                    return;
                }
                break;
            case R.id.send_iv://发布
                Intent intent = new Intent(MaterialActivity.this,SendMaterialMarketActivity.class);
                intent.putExtra("address_id",address_id);
                intent.putExtra("app_cate_id",app_cate_id);
                startActivity(intent);
                break;
        }
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                page++;
                getAppMaterialData("");
            }
        }, 2000);
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                page = 1;
                getAppMaterialData("");
            }
        }, 2000);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


}
